<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : AuthTokenMiddleware.php
 * Created on : 2020-7-25 11:41:46
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace haoteam\http\middleware;

use app\Request;
use haoteam\interfaces\MiddlewareInterface;
use haoteam\service\AdminService;
use haoteam\service\NodeService;
use app\admin\model\AdminUserToken;

/**
 * 后台鉴权路由中间件
 * Class AuthTokenMiddleware
 * Tiger <1192851302@qq.com> 2020-7-25 11:41:46
 */
class AuthTokenMiddleware implements MiddlewareInterface {

    /**
     * 
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @param \Closure $next
     * @param bool $force
     * @return type
     */
    public function handle(Request $request, \Closure $next, bool $force = true) {
        $authInfo = null;
        $token = trim($request->header('token'));
        try {
            $authInfo = AdminUserToken::parseToken($token);
        } catch (\Exception $e) {
            if ($force) {
                return app('json')->make($e->getCode(), $e->getMessage());
            }
        }
        Request::macro('token', function () use (&$token) {
            return $token;
        });
        Request::macro('admin', function () use (&$authInfo) {
            return $authInfo['admin'];
        });
        Request::macro('tokenData', function () use (&$authInfo) {
            return $authInfo['tokenData'];
        });

        Request::macro('adminId', function () use (&$authInfo) {
            return is_null($authInfo) ? 0 : $authInfo['admin']['id'];
        });

        Request::macro('isLogin', function () use (&$authInfo) {
            return !is_null($authInfo);
        });

        Request::macro('isSuper', function () use (&$authInfo) {
            return in_array($authInfo['admin']['roles'], [1, 2]);
        });

        try {
            AdminService::instance()->check(NodeService::instance()->getCurrent(), true);
        } catch (\Exception $e) {
            if ($force) {
                return app('json')->make($e->getCode(), $e->getMessage());
            }
        }

        return $next($request);
    }

}
